//560
class Solution {
    public int subarraySum(int[] nums, int k) {
        int l = 0;
        int r = 0;
        int sum = nums[0];
        int len = nums.length;
        int count = sum == k ? 1 : 0;
        for (int i = 1; i < len; i++) {
            nums[i] = nums[i] + nums[i-1];
            if (nums[i] == k) {
                count++;
            }
        }
        for (int i = 0; i < len; i++) {
            for (int j = i+1; j < len; j++) {
                if (nums[j] - nums[i] == k) {
                    count++;
                }
            }
        }
        return count;
    }
}
//利用前缀和+哈希表优化
class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        Map<Integer, Integer> hash = new HashMap<>();
        hash.put(0, 1);
        int sum = 0;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            if (hash.containsKey(sum-k)) {
                int tmp = hash.get(sum-k);
                count += tmp;
            }
            if (hash.containsKey(sum)) {
                int tmp = hash.get(sum);
                hash.put(sum,tmp+1);
            }
            else {
                hash.put(sum,1);
            }
        }
        return count;
    }
}
//974
class Solution {
    public int subarraysDivByK(int[] nums, int k) {
        int sum = 0;
        int len = nums.length;
        int count = 0;
        Map<Integer, Integer> hash = new HashMap<>();
        hash.put(0, 1);
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            int sum1 = (sum % k + k) % k;
            count += hash.getOrDefault(sum1, 0);
            hash.put(sum1, hash.getOrDefault(sum1, 0)+1);
        }
        return count;
    }
}
//525
class Solution {
    public int findMaxLength(int[] nums) {
        int len = nums.length;
        if (len == 1) {
            return 0;
        }
        for (int i = 0; i < len; i++) {
            if (nums[i] == 0) {
                nums[i] = -1;
            }
        }
        Map<Integer, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 1; i < len; i++) {
            nums[i] = nums[i] + nums[i-1];
        }
        for (int i = 0; i < len; i++) {
            if (nums[i] == 0) {
                max = Math.max(i+1, max);
            }
            else {
                if (map.containsKey(nums[i])) {
                    max = Math.max(i-map.get(nums[i]), max);
                }
                else {
                    map.put(nums[i], i);
                }
            }
        }
        return max;
    }
}
